<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="激光 Port 口" prop="laserPort">
        <el-input
          v-model.trim="queryParams.laserPort"
          placeholder="请输入激光 Port 口"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item label="设备 IP" prop="ip">
        <el-input
          v-model.trim="queryParams.ip"
          placeholder="请输入设备 IP"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item label="设备端口" prop="port">
        <el-input
          v-model.trim="queryParams.port"
          placeholder="请输入设备端口"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadTemplate"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入设备信息"
          url="/api/laser/port/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleLaserAllOn"
          v-hasPermi="['system:info:laser:on']"
        >测试全亮</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleLaserAllOff"
          v-hasPermi="['system:info:laser:off']"
        >测试全灭</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleSingleLaserControl"
          v-hasPermi="['system:info:laser:single']"
        >单个灯控制</el-button>
      </el-col>      
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
        <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" :height="tableHeight" border>
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="自增主键" align="center" prop="id" /> -->
          <el-table-column label="激光 Port 口" align="center" prop="laserPort" />
          <el-table-column label="设备 IP" align="center" prop="ip" />
          <el-table-column label="设备端口" align="center" prop="port" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
            <template #default="scope">
              <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:info:edit']">修改</el-button>
              <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:info:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改激光设备端口信息，存储激光相关设备的Port口、IP和端口号映射关系对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="激光 Port 口" prop="laserPort">
          <el-input v-model="form.laserPort" placeholder="请输入激光 Port 口" />
        </el-form-item>
        <el-form-item label="设备 IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入设备 IP" />
        </el-form-item>
        <el-form-item label="设备端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入设备端口" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 单个激光灯控制对话框 -->
    <el-dialog :title="singleLaserTitle" v-model="showSingleLaserDialog" width="600px" :close-on-click-modal="false">
      <el-form :model="singleLaserForm" ref="singleLaserFormRef" label-width="120px">
        <!-- 端口输入 -->
        <el-form-item label="激光 Port 口" prop="laserPort" required>
          <el-input v-model="singleLaserForm.laserPort" placeholder="请输入激光 Port 口" />
        </el-form-item>
        <!-- SlotID 选择 -->
        <el-form-item label="SlotID" prop="key" required>
          <el-select v-model="singleLaserForm.key" placeholder="请选择 SlotID" @change="handleSlotIdChange">
            <el-option label="SlotID_07（01-50号灯）" value="SlotID_07" />
            <el-option label="SlotID_13（01-20号灯）" value="SlotID_13" />
          </el-select>
        </el-form-item>

    <!-- 全选按钮：仅在激光灯列表生成后显示 -->
    <el-form-item v-if="laserIdList.length > 0">
      <el-button 
        type="primary" 
        plain 
        size="small" 
        @click="handleSelectAllLasers"
        :loading="isProcessing"
      >
        {{ activeLaserIds.length < laserIdList.length ? '全选（逐个点亮）' : '取消全选（逐个关闭）' }}
      </el-button>
    </el-form-item>

        <!-- 激光灯ID列表 -->
        <el-form-item label="选择灯ID" required>
          <div class="laser-id-grid">
            <el-button
              v-for="id in laserIdList"
              :key="id"
              :type="activeLaserIds.includes(id) ? 'success' : 'default'"
              plain
              size="small"
              @click="handleToggleSingleLaser(id)"
            >
              {{ id }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSingleLaserDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>    
  </div>
</template>

<script setup name="RaserPortInfo">
import { listInfo, getInfo, delInfo, addInfo, updateInfo, laserAllLightOn, laserAllLightOff, switchSingleLaser } from "@/api/work/raserPortInfo"

const { proxy } = getCurrentInstance()

const infoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    laserPort: null,
    ip: null,
    port: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 单个激光灯控制相关数据
const isProcessing = ref(false) // 用于控制全选过程中的状态锁定
const showSingleLaserDialog = ref(false) // 单个灯控制对话框显示状态
const singleLaserTitle = ref("单个激光灯控制") // 对话框标题
const singleLaserFormRef = ref(null) // 表单引用
const singleLaserForm = ref({
  laserPort: '', // 激光端口
  key: '' // SlotID（SlotID_07/SlotID_13）
})
const activeLaserIds = ref([]) // 记录已点亮的灯ID（数组存储，保证响应式正常）
const laserIdList = ref([]) // 动态生成的灯ID列表（根据SlotID切换）

/**
 * 打开单个激光灯控制对话框
 * 功能：重置表单数据和灯状态，显示对话框
 */
function handleSingleLaserControl() {
  // 重置表单数据
  singleLaserForm.value = { laserPort: '', key: '' }
  // 清空已点亮的灯ID记录
  activeLaserIds.value = []
  // 清空灯ID列表
  laserIdList.value = []
  // 显示对话框
  showSingleLaserDialog.value = true
}

/**
 * 全选/取消全选激光灯（自动逐个触发）
 */
async function handleSelectAllLasers() {
  // 校验表单
  if (!singleLaserForm.value.laserPort) {
    proxy.$modal.msgWarning('请输入激光 Port 口')
    return
  }
  if (!singleLaserForm.value.key) {
    proxy.$modal.msgWarning('请选择 SlotID')
    return
  }
  
  if (isProcessing.value) return
  isProcessing.value = true
  
  const targetState = activeLaserIds.value.length < laserIdList.value.length
  const total = laserIdList.value.length
  let successCount = 0
  
  try {
    // 逐个处理每个灯
    for (const [index, laserId] of laserIdList.value.entries()) {
      // 进度提示（使用项目中可用的提示方式）
      if (proxy.$message) {
        proxy.$message({
          message: `正在${targetState ? '点亮' : '关闭'}第${index + 1}/${total}个灯...`,
          type: 'info',
          duration: 500  // 短时间提示，避免堆积
        })
      }
      
      // 构建请求参数
      const requestData = {
        laserPort: singleLaserForm.value.laserPort,
        bodyList: [{
          key: singleLaserForm.value.key,
          laseID: laserId,
          state: targetState ? 1 : 0
        }]
      }
      
      // 调用接口
      const res = await switchSingleLaser(requestData)
      
      // 处理结果
      if (res && res.errCode === '1') {
        successCount++
        if (targetState) {
          if (!activeLaserIds.value.includes(laserId)) {
            activeLaserIds.value.push(laserId)
          }
        } else {
          activeLaserIds.value = activeLaserIds.value.filter(id => id !== laserId)
        }
      }
      
      // 间隔100ms，避免请求过于密集
      await new Promise(resolve => setTimeout(resolve, 100))
    }
    
    // 最终结果提示
    proxy.$modal.msgSuccess(
      `${targetState ? '全选' : '取消全选'}完成，成功${targetState ? '点亮' : '关闭'}${successCount}/${total}个灯`
    )
  } catch (error) {
    proxy.$modal.msgError(`操作失败：${error.message || '未知错误'}`)
  } finally {
    isProcessing.value = false
  }
}

/**
 * SlotID切换事件
 * 功能：根据选择的SlotID，动态生成对应范围的激光灯ID列表
 */
function handleSlotIdChange() {
  // 切换SlotID时，清空已点亮状态
  activeLaserIds.value = []
  // 根据SlotID生成对应灯ID（两位数字格式：01-50/01-20）
  if (singleLaserForm.value.key === 'SlotID_07') {
    // SlotID_07对应01-50号灯
    laserIdList.value = Array.from({ length: 50 }, (_, i) => (i + 1).toString().padStart(2, '0'))
  } else if (singleLaserForm.value.key === 'SlotID_13') {
    // SlotID_13对应01-20号灯
    laserIdList.value = Array.from({ length: 20 }, (_, i) => (i + 1).toString().padStart(2, '0'))
  } else {
    // 未选择SlotID时，清空列表
    laserIdList.value = []
  }
}

/**
 * 切换单个激光灯状态（点动控制）
 * 功能：点击灯ID按钮，切换该灯的开关状态（亮→灭/灭→亮）
 * @param {String} laseID - 激光灯ID（如01、02）
 */
function handleToggleSingleLaser(laseID) {
  // 校验表单必填项
  if (!singleLaserForm.value.laserPort) {
    proxy.$modal.msgWarning('请输入激光 Port 口')
    return
  }
  if (!singleLaserForm.value.key) {
    proxy.$modal.msgWarning('请选择 SlotID')
    return
  }

  // 判断当前灯是否已点亮
  const isActive = activeLaserIds.value.includes(laseID)
  // 构建请求参数（符合SwitchLaserLightDTO格式）
  const requestData = {
    laserPort: singleLaserForm.value.laserPort,
    bodyList: [
      {
        key: singleLaserForm.value.key,
        laseID: laseID,
        state: isActive ? 0 : 1 // 状态切换：已点亮→0（灭），未点亮→1（亮）
      }
    ]
  }

  // 调用单个灯控制接口
  switchSingleLaser(requestData).then(res => {
    // 接口调用成功且返回成功状态
    if (res && res.errCode === '1') {
      if (isActive) {
        // 关闭灯：从已点亮列表中移除该ID
        activeLaserIds.value = activeLaserIds.value.filter(id => id !== laseID)
        proxy.$modal.msgSuccess(`激光灯${laseID}已关闭`)
      } else {
        // 开启灯：将该ID添加到已点亮列表
        activeLaserIds.value.push(laseID)
        proxy.$modal.msgSuccess(`激光灯${laseID}已开启`)
      }
    } else {
      // 接口调用失败，提示错误信息
      proxy.$modal.msgError(res?.msg || `操作激光灯${laseID}失败`)
    }
  }).catch(() => {
    // 接口调用异常处理
    proxy.$modal.msgError('接口调用异常')
  })
}

//测试激光全亮
function handleLaserAllOn() {
  proxy.$prompt('请输入激光灯端口号', '测试全亮', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[A-Za-z0-9]+$/,
    inputErrorMessage: '端口号只能包含字母和数字'
  }).then(({ value }) => {
    laserAllLightOn(value).then(res => {
      if (res.errCode === '1') {
        proxy.$modal.msgSuccess('激光全亮指令发送成功')
      } else {
        proxy.$modal.msgError(res.msg || '激光全亮指令发送失败')
      }
    }).catch(() => {
      proxy.$modal.msgError('接口调用异常')
    })
  }).catch(() => {
    proxy.$modal.msgInfo('已取消操作')
  })
}

//测试激光全灭
function handleLaserAllOff() {
  proxy.$prompt('请输入激光灯端口号', '测试全灭', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[A-Za-z0-9]+$/,
    inputErrorMessage: '端口号只能包含字母和数字'
  }).then(({ value }) => {
    laserAllLightOff(value).then(res => {
      if (res.errCode === '1') {
        proxy.$modal.msgSuccess('激光全灭指令发送成功')
      } else {
        proxy.$modal.msgError(res.msg || '激光全灭指令发送失败')
      }
    }).catch(() => {
      proxy.$modal.msgError('接口调用异常')
    })
  }).catch(() => {
    proxy.$modal.msgInfo('已取消操作')
  })
}

/** 查询激光设备端口信息，存储激光相关设备的Port口、IP和端口号映射关系列表 */
function getList() {
  loading.value = true
  listInfo(queryParams.value).then(res => {
    if (res.errCode === '1') {
      infoList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    laserPort: null,
    ip: null,
    port: null,
    remark: null
  }
  proxy.resetForm("infoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加激光设备信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getInfo(_id).then(res => {
    form.value = res.data.laserPortInfo
    open.value = true
    title.value = "修改激光设备信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateInfo(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addInfo(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除激光设备端口信息，存储激光相关设备的Port口、IP和端口号映射关系编号为"' + _ids + '"的数据项？').then(function() {
    return delInfo(_ids)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('api/laser/port/export', {
    ...queryParams.value
  }, `info数据_${new Date().getTime()}.xlsx`)
}

getList()

// 下载模板
const downloadTemplate = async() => {
  proxy.download('/api/laser/port/downloadTemplate', {}, `info模板_${new Date().getTime()}.xlsx`)
}
// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}
// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}
</script>

<style scoped>
/* 激光灯ID按钮网格布局 - 修复排版对齐问题 */
.laser-id-grid {
  display: flex;
  flex-wrap: wrap; /* 自动换行 */
  gap: 8px; /* 按钮间距，保持一致 */
  margin-top: 10px;
  max-height: 180px;
  overflow-y: auto;
  padding: 5px;
}

/* 固定按钮宽度，确保所有按钮大小一致 */
.laser-id-grid .el-button--small {
  width: 35px; /* 固定宽度，根据需求微调 */
  height: 32px; /* 固定高度，与宽度匹配 */
  padding: 0; /* 清除默认内边距 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  flex-shrink: 0; /* 禁止按钮缩小 */
  margin: 0;
}

/* 可选：添加加载状态样式 */
.laser-id-grid .el-button--loading {
  opacity: 0.7;
  cursor: not-allowed;
}
</style>